const http = require("../../api/http")
const app = getApp();
Page({
  data: {
    activeIndex: 0,
    navbar: app.globalData.navbar,
    list: [], // 成品集合
  },
  onReady() {
    wx.setEnableDebug({
      enableDebug: true
    })
  },
  onShow() {
    this.setData({
      activeIndex: app.globalData.activeTabIndex
    })
    this.login()
  },
  onPullDownRefresh() {
    this.getPrintDataForPage()
    wx.stopPullDownRefresh()
  },
  login() {
    const token = wx.getStorageSync('cookies')
    const _this = this
    if (!token) {
      this.setData({
        showLoginTip: true
      })
      http.login().then(() => {
        _this.getPrintDataForPage()
      })
    } else {
      _this.getPrintDataForPage()
    }
  },
  getPrintDataForPage() {
    http.post('/print-task/getPrintTaskPage', {
      pageNum: 1,
      pageSize: 10
    }).then((res) => {
      console.log(res)
      const data = res.data.list || []
      const imageList = []
      for (let template of data) {
        if (template.thumbnailId) {
          const image = {}
          image.src = `${app.globalData.server}/file/downLoad?fileId=${template.thumbnailId}&type=2`
          image.templateId = template.templateId
          image.id = template.id
          imageList.push(image)
        }
      }
      this.setData({
        list: imageList
      })
    })
  },
  /**
   * 长按模板
   * @param {Object} event 
   */
  templateLonggressHandle(event) {
    const { id } = event.currentTarget.dataset
    let list = this.data.list
    const _this = this
    if (id) {
      wx.showActionSheet({
        itemList: ['删除'],
        success(res) {
          if (res.tapIndex === 0) {
            http.post("/print-task/deleteById", { id })
              .then((res) => {
                list = list.filter(item => item.id !== id)
                _this.setData({ list })
                app.globalData.reload = true
              })
          }
        },
        fail(res) {
          console.log(res.errMsg)
        }
      })
    }
  },
  templateDetail: function (event) {
    const { id, templateId } = event.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/template/template?templateId=${templateId}&printId=${id}`,
    })
  },
})